import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()
  // set page title
  // console.log(to)
  // document.title = getPageTitle(to.meta.title)
  const str = to.meta.title
  if (str && str.indexOf('-') !== -1) {
    const arr = str.split('-')
    const title = arr[0]
    const tmp = to.params.title ? to.params.title : '添加'
    to.meta.title = title + '-' + tmp
  } else {
    document.title = getPageTitle(to.meta.title)
  }

  // determine whether the user has logged in
  const hasToken = getToken()
  const loadUserInfo = () => {
    store.dispatch('user/getInfo').then((res) => {
      store.dispatch('permission/generateRoutes', res.permissions).then(accessRoutes => {
        // console.log(accessRoutes)
        router.addRoutes(accessRoutes)
        // console.log(router.getList())
        next({ ...to, replace: true })
      })
    }).catch((error) => {
      if (error.code !== undefined && error.code === 4000) {
        // alert('登录超时，请重新登录')
        store.dispatch('user/resetToken').then(() => {
          if (whiteList.indexOf(to.path) !== -1) {
            next()
          } else {
            location.href = store.state.settings.conf.login
            // console.log(store.state.settings)
            // next(`/login?redirect=${to.path}`)
            NProgress.done()
          }
        })
        return
      }
      console.error(error)
    })
  }
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          loadUserInfo()
        } catch (error) {
          console.log(error)
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          location.href = store.state.settings.conf.login
          // next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    loadUserInfo()
    // if (whiteList.indexOf(to.path) !== -1) {
    //   // in the free login whitelist, go directly
    //   next()
    // } else {
    //   // other pages that do not have permission to access are redirected to the login page.
    //   next(`/login?redirect=${to.path}`)
    //   NProgress.done()
    // }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
